package com.whenjun.interceptor;

import cn.dev33.satoken.context.SaHolder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.whenjun.thread.AsyncServiceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Auther: whenjun
 * @Date: 2023/6/5 0005 17:29
 * @Description:
 */
@ControllerAdvice
public class ResponseBody implements ResponseBodyAdvice<Object> {

    @Autowired
    private AsyncServiceResponse asyncServiceResponse;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        String requestId = SaHolder.getStorage().getString("requestId");
        String respBody = JSON.toJSONString(body, SerializerFeature.DisableCircularReferenceDetect);

        asyncServiceResponse.updateRespBodyByPrimaryKey(requestId, respBody);

        return body;
    }
}
